package com.bsoft.gol.hcs.common.service.impl;

import com.bsoft.gol.hcs.clinical.bean.req.QueryMedicalSkillListReq;
import com.bsoft.gol.hcs.clinical.bean.vo.ConsultAskVo;
import com.bsoft.gol.hcs.clinical.bean.vo.DepartmentListVo;
import com.bsoft.gol.hcs.clinical.dao.ConsultAskDAO;
import com.bsoft.gol.hcs.clinical.entity.HoConsultAsk;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.bsoft.gol.hcs.common.bean.request.FamilyMemberRequest;
import com.bsoft.gol.hcs.common.bean.request.GetFusConsultIdRequest;
import com.bsoft.gol.hcs.common.bean.response.AccountFamilyResponse;
import com.bsoft.gol.hcs.common.bean.response.FusConsultResponse;
import com.bsoft.gol.hcs.common.bean.response.ParameterResponse;
import com.bsoft.gol.hcs.common.dao.FusConsultAskDAO;
import com.bsoft.gol.hcs.common.entity.FusConsultAsk;
import com.bsoft.gol.hcs.common.service.ICommonService;
import ctd.util.JSONUtils;
import ctd.util.annotation.RpcService;
import com.bsoft.gol.hcs.enumcase.PlatformEnum;
import com.bsoft.gol.hcs.enumcase.InterfaceTypeEnum;
import hcn.util.BaseResponse;
import hcn.service.commonClinical.qo.SysParameterRequest;
import hcn.util.ResultCode;
import com.bsoft.gol.hcs.service.rpc.IBaseParameterService;
import com.bsoft.gol.hcs.his.service.IMedicalSkillsHisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.bsoft.gol.hcs.utils.CommonUtils;
import com.bsoft.gol.hcs.utils.Constants;
import org.atag.util.http.KdHttpClientUtil;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 流调服务层
 * @Author: zhaorb
 * @Date: 2020/7/6 16:46
 **/
@Service
public class CommonService implements ICommonService {
    private static final Logger logger = LoggerFactory.getLogger(CommonService.class);

    @Autowired
    FusConsultAskDAO fusConsultAskDAO;

    @Autowired
    ConsultAskDAO consultAskDAO;

    @Autowired
    IBaseParameterService baseParameterService;

    @Autowired
    private IMedicalSkillsHisService medicalSkillsHisService;

    @Value("${project_source}")
    private String projectSource;

    @Override
    public BaseResponse<List<AccountFamilyResponse>> findFamilyMemberList(FamilyMemberRequest request) {
        return baseParameterService.findFamilyMemberList(request);
    }

    @Override
    public BaseResponse<List<ParameterResponse>> getSysParameterList(SysParameterRequest request) {
        return baseParameterService.getSysParameterList(request);
    }

    @Override
    @RpcService
    public BaseResponse  getFusConsultId(GetFusConsultIdRequest request) {

        BaseResponse result = new BaseResponse<>();
        BaseResponse consultAskVo = new BaseResponse<>();
        FusConsultAsk savefusConsultAskEntity =new FusConsultAsk();


        FusConsultResponse fusConsultResponse=new FusConsultResponse();
        QueryMedicalSkillListReq qasrequest=new QueryMedicalSkillListReq();
        List<DepartmentListVo> departmentListVos = null;

        FusConsultAsk fusConsultAskEntity = fusConsultAskDAO.getConsultInfoByDoctorId(request.getDoctorId(),request.getConsultMpiId());

        if (fusConsultAskEntity == null) {
           // return result.setResultError("成员不存在");
        }else{
            if(CommonUtils.isEmpty(fusConsultAskEntity.getFinishedTime())){
                qasrequest.setBussType(request.getType());
                qasrequest.setConsultId(fusConsultAskEntity.getConsultId());

                ConsultAskVo vo=new ConsultAskVo() ;
                try {
                    if (Constants.HOL.equals(projectSource)) {
                        logger.info("进入互联网医院");
                        HoConsultAsk consultAsk = consultAskDAO.getConsultAskAll(qasrequest);
                        BeanUtils.copyProperties(consultAsk, vo);
                        vo.setConsultId(consultAsk.getConsultId() + "");
                    } else {
                        logger.info("进入智慧健康通");
                        vo = medicalSkillsHisService.getHcnConsultAsk(qasrequest).getData();
                    }
                    //查询到聊天结束，更新专科随访中的结束时间
                    if (CommonUtils.isNotEmpty(vo) && CommonUtils.isNotEmpty(vo.getFinishedTime())) {
                        fusConsultAskDAO.updateById(vo.getFinishedTime(),fusConsultAskEntity.getFusConsultAskId());
                    }else{//直接返回consultId
                        BaseResponse<FusConsultResponse>  baseResp = new BaseResponse();
                        fusConsultResponse.setConsultId(fusConsultAskEntity.getConsultId()+"");
                        fusConsultResponse.setOrganizationId(fusConsultAskEntity.getOrgId());
                        baseResp.setData(fusConsultResponse);
                        return baseResp;
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    result.setMessage("获取问诊信息失败");
                    result.setCode(ResultCode.ERROR);
                    return result;
                }
            }
        }

        try {
            String url ="";
            if (Constants.HOL.equals(projectSource)){
                logger.info("进入互联网医院");
                //doctorListVos = sysParameterDAO.queryDoctorList(request);
                logger.info(System.getProperty("java.class.path") + "");
                  url = Constants.HOL_FAMILY_URL + Constants.GET_FUS_CONSULT_ID;
            } else {
                logger.info("进入智慧健康通");
                logger.info(System.getProperty("java.class.path") + "");
                  url = Constants.GOL_CLIENT_URL + Constants.GET_FUS_CONSULT_ID;
            }
                logger.info("url:{}", url);
                String str = null;
                try {
                    str = KdHttpClientUtil.doPost(url, JSONUtils.writeValueAsString(request),null);
                } catch (Exception e) {
                    result.setMessage(Constants.JSON_ANALYSIS_ERR + e.getMessage());
                    result.setCode(Constants.ERR_CODE);
                }
                if (CommonUtils.isNotEmpty(str)) {
                    JSONObject jsonObject = JSONObject.parseObject(str);
                    logger.info("str:{}", str);
                    logger.info("jsonObject:{}", jsonObject.toJSONString());
                    try {
                        if (CommonUtils.isNotEmpty(jsonObject)) {
                            JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                            if (CommonUtils.isNotEmpty(jsonObject1)) {
                                fusConsultResponse = JSONObject.parseObject(jsonObject1.toString(), FusConsultResponse.class);
                                result.setData(fusConsultResponse);
                                result.setCode(ResultCode.SUCCESS);
                            }else{
                                result.setCode(ResultCode.ERROR);
                                result.setMessage(jsonObject.getString("message"));
                                return result;
                            }
                        } else {
                            result.setCode(ResultCode.ERROR);
                            result.setMessage(jsonObject.getString("message"));
                            return result;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        result.setMessage(Constants.JSON_ANALYSIS_ERR + e.getMessage());
                        result.setCode(Constants.ERR_CODE);
                        return result;
                    }
                    logger.info("queryDoctorList:{}", result);
                   // return result;
                }

            if (CommonUtils.isNotEmpty(fusConsultResponse)) {
                savefusConsultAskEntity.setConsultId(fusConsultResponse.getConsultId());
                savefusConsultAskEntity.setAge(request.getAge());
                savefusConsultAskEntity.setConsultMpiId(request.getConsultMpiId());
                savefusConsultAskEntity.setDoctorId(request.getDoctorId());
                savefusConsultAskEntity.setConsultType(request.getConsultType());
                savefusConsultAskEntity.setCreateUserId(request.getDoctorId());
                savefusConsultAskEntity.setDeptId(request.getDepartmentId());
               savefusConsultAskEntity.setOrgId(request.getOrganizationId());
                savefusConsultAskEntity.setGender(request.getGender());
                savefusConsultAskEntity.setPatientIdentityCardType(request.getIdCardType());
                savefusConsultAskEntity.setPatientIdentityCardNumber(request.getIdCardNo());
                savefusConsultAskEntity.setPatientMedicalCardNumber(request.getPatientMedicalCardNumber());
                savefusConsultAskEntity.setPatientMedicalCardType(request.getPatientMedicalCardType());
                savefusConsultAskEntity.setCreateTime(new Timestamp(System.currentTimeMillis()));
                fusConsultAskDAO.save(savefusConsultAskEntity);
                result.setData(fusConsultResponse);
                result.setCode(ResultCode.SUCCESS);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage("获取记录失败");
            result.setCode(ResultCode.ERROR);
        }


        return result;
       /* String jsonContext = " {\n" +
                "    \"consultId\": \"ff51cee3-5817-4a9d-b24e-0a4c6cc88888\",\n" +
                "    \"organizationId\": \"1\"\n" +
                "  }";

        fusConsultResponse = JSONArray.parseObject(jsonContext, FusConsultResponse.class);
        BaseResponse<FusConsultResponse>  baseResponse = new BaseResponse();
        baseResponse.setData(fusConsultResponse);
        return baseResponse;*/

    }

    @Override
    public ParameterResponse getParameterResponse(String params,String orgId){
        ParameterResponse parameterResponse = null;
        SysParameterRequest sysParameterRequest = new SysParameterRequest();
        sysParameterRequest.setOrganizationId(orgId);
        sysParameterRequest.setType(projectSource);
        List<String> strings = new ArrayList<>();
        if(InterfaceTypeEnum.GOL.getCode().equals(projectSource)){
            strings.add( PlatformEnum.getHOL(params));
        }else if(InterfaceTypeEnum.HOL.getCode().equals(projectSource)){
            strings.add( PlatformEnum.valueOf(params).getHOL());
        }
        sysParameterRequest.setParameterKeyList(strings);
        if(CommonUtils.isEmpty(orgId)){
            sysParameterRequest.setOrganizationType(1);
        }else{
            sysParameterRequest.setOrganizationType(2);
        }

        BaseResponse<List<ParameterResponse>> parameterResponses = this.getSysParameterList(sysParameterRequest);
        if(CommonUtils.isNotEmpty(parameterResponses)){
            List<ParameterResponse> parameterResponseList = parameterResponses.getData();
            if(CommonUtils.isNotEmpty(parameterResponseList)){
                parameterResponse =  parameterResponseList.get(0);
            }
        }
        return parameterResponse;
    }

    /**
     * @description: 根据机构代码，获取系统参数的参数值
     * @author: chenJij@bsoft.com.cn
     * @date: 2020/11/4 11:07
     * @param: organizationId
     * @param: platformEnum
     * @return: java.lang.String
     */
    @Override
    public String getParameterValue(String organizationId, PlatformEnum platformEnum){
        ParameterResponse parameterResponse = getParameterResponse(platformEnum.name(),organizationId);
        if(CommonUtils.isNotEmpty(parameterResponse)){
            return parameterResponse.getParameterValue();
        }
        return null;
    }
}

